package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.zb.client.SkuFeignClient;
import com.zb.service.PageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements PageService {

    @Autowired(required = false)
    private SkuFeignClient skuFeignClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${page.path}")
    private String path;

    private Map<String, Object> getData(String skuId) {
        Map<String, Object> item = skuFeignClient.item(skuId);
        Map<String, Object> skuDTO = (Map<String, Object>) item.get("skuDTO");
        Map<String, Object> spuDTO = (Map<String, Object>) item.get("spuDTO");
        String[] images = skuDTO.get("images").toString().split(",");
        item.put("images", images);
        String specJson = spuDTO.get("specItems").toString();
        Map<String, List<String>> specMap = JSON.parseObject(specJson, Map.class);
        item.put("specMap", specMap);
        return item;
    }


    @Override
    public void createPage(String skuId) {
        //获取上下对象
        Context context = new Context();
        //存储页面上的数据
        context.setVariables(getData(skuId));
        File file = new File(path);
        //文件路径不存在
        if (!file.exists()) {
            file.mkdir();//创建路径
        }
        //生成的文件
        File myFile = new File(file, skuId + ".html");
        try {
            //将文件转换成数据流
            PrintWriter printWriter = new PrintWriter(myFile, "UTF-8");
            //调用引擎生成静态页面
            //item 模板页面
            templateEngine.process("item", context, printWriter);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }
}
